package com.yxh.www.author.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxh.www.author.domain.SmOrganize;
import com.yxh.www.author.domain.SmUser;
import com.yxh.www.author.mapper.SmOrganizeMapper;
import com.yxh.www.author.mapper.SmUserMapper;
import com.yxh.www.author.service.SmOrganizeService;
import com.yxh.www.common.result.Result;
import com.yxh.www.common.result.ResultBuilder;
import com.yxh.www.common.result.ResultEnum;
import com.yxh.www.mysql.base.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统组织-RBAC 服务实现类
 * </p>
 *
 * @author Yangxiaohui
 * @since 2020-05-09
 */
@Service
public class SmOrganizeServiceImpl extends BaseServiceImpl<SmOrganizeMapper, SmOrganize> implements SmOrganizeService {

    private final SmUserMapper smUserMapper;

    public SmOrganizeServiceImpl(SmUserMapper smUserMapper) {
        this.smUserMapper = smUserMapper;
    }

    /**
     * 新增系统组织
     *
     * @param organizeName 组织名称
     * @param parentId     上级组织ID
     * @param adminUser    组织管理（负责人）
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> addSmOrganize(String organizeName, String parentId, String adminUser) {
        // 判断该用户是否存在
        int countSmUserById = smUserMapper.selectCount(new QueryWrapper<SmUser>()
                .eq("id", adminUser)
                .eq("user_status", "0")
        );
        if (countSmUserById == 0) {
            return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "无效的组织负责人");
        }
        // 判断组织是否重复
        int countOrganizeByOrganizeNameAndParentId = baseMapper.selectCount(new QueryWrapper<SmOrganize>()
                .eq("organize_name", organizeName)
                .eq("parent_id", parentId)
        );
        if (countOrganizeByOrganizeNameAndParentId > 0) {
            return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "增加组织失败：重复的组织！");
        }
        SmOrganize smOrganize = new SmOrganize(organizeName, parentId, adminUser);
        smOrganize.setCreateTime(LocalDateTime.now());
        return smOrganize.insert() ? ResultBuilder.success() : ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "组织增加失败！");
    }

    /**
     * 根据组织ID修改组织信息
     *
     * @param id             组织ID
     * @param organizeStatus 组织状态（0：正常；1：失效）
     * @param adminUser      组织负责人-管理人员-部门主管
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> modifySmOrganize(String id, String organizeStatus, String adminUser) {
        SmOrganize smOrganize = new SmOrganize().setId(id).setOrganizeStatus(organizeStatus).setAdminUser(adminUser);
        return smOrganize.updateById() ? ResultBuilder.success() : ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "组织修改失败！");
    }

    /**
     * 根据组织ID删除组织
     *
     * @param ids 组织ID集合
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> removeSmOrganize(String[] ids) {
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        return ResultBuilder.success();
    }

    /**
     * 查询组织列表
     *
     * @param organizeName 组织名称    模糊匹配
     * @param parentId     父组织ID   精准匹配
     * @param adminUser    adminUser 组织负责人-管理人员-部门主管   精准匹配
     * @return 统一响应 {@link Result<   List   >} 实体 {@link SmOrganize}
     */
    @Override
    public Result<List<SmOrganize>> listSmOrganize(String organizeName, String parentId, String adminUser) {
        QueryWrapper<SmOrganize> queryWrapper = buildListSmOrganizeWrapper(organizeName, parentId, adminUser);
        return ResultBuilder.success(baseMapper.selectList(queryWrapper));
    }

    /**
     * 分页查询系统组织列表
     *
     * @param organizeName 组织名称    模糊匹配
     * @param parentId     父组织ID   精准匹配
     * @param adminUser    adminUser 组织负责人-管理人员-部门主管   精准匹配
     * @param pageNum      页码          默认值 1
     * @param pageSize     页面数据长度    默认值 20
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> pageSmOrganize(String organizeName, String parentId, String adminUser, Long pageNum, Long pageSize) {
        QueryWrapper<SmOrganize> queryWrapper = buildListSmOrganizeWrapper(organizeName, parentId, adminUser);
        return ResultBuilder.success(baseMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper));
    }

    private QueryWrapper<SmOrganize> buildListSmOrganizeWrapper(String organizeName, String parentId, String adminUser) {
        QueryWrapper<SmOrganize> queryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotBlank(organizeName)){
            queryWrapper.like("organize_name",organizeName);
        }
        if (StringUtils.isNotBlank(parentId)){
            queryWrapper.like("parent_id",parentId);
        }
        if (StringUtils.isNotBlank(adminUser)){
            queryWrapper.like("admin_user",adminUser);
        }
        return queryWrapper;
    }
}
